package org.dev.app.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;

public class QiniuUtils {

    private static Configuration cfg = new Configuration(Zone.zone1());

    static {
        /**
         * 取消使用 https 域名，七牛云上传不使用 https
         * 因为一些 jvm 证书库内的 ssl 证书可能有问题，导致七牛云上传失败
         */
        cfg.useHttpsDomains = false;
    }

    private static UploadManager uploadManager = new UploadManager(cfg);

    public static String upload(InputStream inputStream, String file, String qiniuAccessKey, String qiniuSecretKey, String qiniubucketname) throws IOException {
        String key = null;//文件路径
        try {
            //实例化一个BucketManager对象

            Auth auth = Auth.create(qiniuAccessKey, qiniuSecretKey);
            String uploadToken = auth.uploadToken(qiniubucketname);
            Response response = uploadManager.put(inputStream, file, uploadToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            key = putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
        return key;
    }

    public static void deleteFile(String key, String bucketname, String qiniuAccessKey, String qiniuSecretKey) {
        try {
            //调用delete方法移动文件
            Auth auth = Auth.create(qiniuAccessKey, qiniuSecretKey);
            BucketManager bucketManager = new BucketManager(auth, cfg);
            bucketManager.delete(bucketname, key);
        } catch (QiniuException e) {
            //捕获异常信息
            Response r = e.response;
            System.out.println(r.toString());

        }
    }
}
